import React, { FC, useEffect, useRef } from 'react';
import _ from 'lodash';
import MyHead from '../../components/MyHead';
import PassInput from '../../components/PassInput';
import { useSearchParams } from 'react-router-dom'
import {
    Form,
    Input,
    Button,
  } from 'antd-mobile'
import { ShowMessage } from '../../utils/message';
import { LoginAPI } from '../../api/api';
import { useLocalData } from '../../hooks/useLocalData';
import { useCommonFunc } from '../../hooks/useCommon';
import { UserInfoType } from './Reg';

interface MobileValue {
    preValue: string
    realValue: string
}


const Login = () => {
    const [query] = useSearchParams()
    const formRef:any = useRef()
    const [ form ] = Form.useForm()
    const { gotopage } = useCommonFunc()
    const {
        account,
        setToken,
        setAccount,
    } = useLocalData()

    const onFinish = async(value: UserInfoType) => {
                const res:any = await LoginAPI({
                    username:value.username,
                    password:value.password,
                })
                if(res.code == "200"){
                    gotopage('/app/mine')
                    setToken(res.token)
                    setAccount(value.username)
                }else{  
                    ShowMessage(res.msg)
                }
            }

    useEffect(()=>{
        if(query.get('userName')){
            form.setFieldValue("userName",query.get('userName'))
        }else{
            form.setFieldValue('userName',account)
        }
    })

    return (
        <div className='spage reg'>
        <MyHead title='登陆' />
        <div className='reg-box' style={{ padding: 15}}>
            <Form
                ref={formRef}
                form={form}
                layout='vertical'
                onFinish={onFinish}
                initialValues={{
                    sex:'0',
                }}
                footer={
                    <div>
                        <Button block type='submit' color='primary' size='large'>
                            提交
                        </Button>
                        <Button block type='reset' color='danger' className='mt10' size='large'>
                            重置
                        </Button>
                    </div>
                }
            >
                <Form.Header>登陆账号</Form.Header>
                <Form.Item
                        label='用户名'
                        name='username'
                        rules={[{ required: true, message: '用户名不能为空!' }]}
                    >
                        <Input placeholder='请输入用户名' autoComplete='true' clearable/>
                    </Form.Item>
                <PassInput
                name='password'
                />
            </Form>
        </div>
    </div>
    );
};

export default Login;